function Texture(layer, url, x, y, w, h, sx, sy, sw, sh) {
	this.layer = layer;
	this.url = url;
	var self = this;
	ImageLoader.fetch(this.url, function (img) { self.image = img; });
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
	this.mode = "source-over";
	this.alpha = 1;
}

Texture.prototype = {
	setBlendMode: function (mode, alpha) {
		this.mode = mode == "ADD" ? "lighter" : "source-over";
		this.alpha = alpha || 1;
		if (this.alpha < 0) this.alpha = 0;
		if (this.alpha > 1) this.alpha = 1;
	},
	setTexCoord: function (sx, sy, sw, sh) {
		// here we check for inverted textures
		var inverted_x = 0;
		var inverted_y = 0;
		if (sw < 0) {
			inverted_x ++;
			this.sx = sw + sx;
			this.sw = -sw;
		} else {
			this.sx = sx;
			this.sw = sw;
		}
		if (sh < 0) {
			inverted_y ++;
			this.sy = sh + sy;
			this.sh = -sh;
		} else {
			this.sy = sy;
			this.sh = sh;
		}
		if (this.w < 0) {
			inverted_x ++;
			this.w = -this.w
		}
		if (this.h < 0) {
			inverted_y ++;
			this.h = -this.h
		}
		if (inverted_x == 1) {
			this.scale_x = -1;
			this.x = -this.x -this.w;
		} else {
			this.scale_x = 1;
		}
		if (inverted_y == 1) {
			this.scale_y = -1;
			this.y = -this.y -this.h;
		} else {
			this.scale_y = 1;
		}
	},
	draw: function (ctx) {
		if (this.image && this.image.width > 0 && this.image.height > 0) {
			ctx.save();
			try {
				ctx.scale(this.scale_x, this.scale_y);
				ctx.globalCompositeOperation = this.mode;
				ctx.globalAlpha = this.alpha;
				ctx.drawImage(this.image,
					this.sx, this.sy, this.sw, this.sh,
					this.x, this.y, this.w, this.h);
			} catch (e) {
				//~ alert(e);
			}
			ctx.restore();
		}
	},
};

